#include "heartcurve.h"

// AsyncLayer(1) 参数1设置图层为异步绘制模式
HeartCurve::HeartCurve() : AsyncLayer(1) {}

// 自定义绘制内容
void HeartCurve::draw(QPixmap &pixmap)
{
    QPainter painter(&pixmap);
    painter.setRenderHint(QPainter::Antialiasing, true);

    // 伸缩系数
    static double factor = -6;
    // 伸缩方向
    static int direct = 1;

    // 模拟非线性伸缩
    auto sigmoid = [](double x) -> double { return 1 / (1 + std::exp(-x)); };

    // 适应窗口变化
    double scale = (pixmap.width() < pixmap.height()) ? pixmap.width() : pixmap.height();

    // 计算伸缩系数
    scale /= 60;
    scale += (10 * sigmoid(factor));

    // 计算心形曲线点集，模拟密集运算
    QPolygonF points;
    double t = 0;
    while (t < 2 * M_PI)
    {
        double x = 16 * std::pow(std::sin(t), 3);
        double y = 13 * std::cos(t) - 5 * std::cos(2 * t) - 2 * std::cos(3 * t) - std::cos(4 * t);
        points.append(QPointF(x * scale + pixmap.width() / 2, -y * scale + pixmap.height() / 2));
        t += 0.005;
    }

    // 设置画笔
    QPen pen = painter.pen();
    pen.setColor(Qt::red);
    pen.setWidth(4.0);
    painter.setPen(pen);

    // 绘制心形曲线
    painter.drawPolyline(points);

    // 更新曲线参数
    if (direct == 1) {
        if (factor < 6) {
            factor += 0.2;
        } else {
            direct = -1;
        }
    } else {
        if (factor > -6) {
            factor -= 0.2;
        } else {
            direct = 1;
        }
    }
}

